import {debounce, formatNumber} from "@/components/QueryTableRender/utils";
import {REF_PAGEBAR_C, REF_TOOLBAR_C, REF_BATCHBAR_C} from "@/components/QueryTableRender/config";
import {checkButtonPermission} from "@/directive/permission/permission";

export function generateSubmitterNode(render, vm) {
    const h = render ? render : vm.$createElement
    return h('div', {
        'class': 'no-margin-bottom',
        style: {
            marginLeft: 'auto',
            textAlign: 'right',
            flex: `0 0 ${100 / vm.spanConfig.span}%`
        }
    }, [
        h('el-form-item', {
            key: 'operator',
            props: {
                labelWidth: '100px'
            }
        }, [
            h('span', {style: {opacity: 0}, slot: 'label'}, 'lb'),
            h('el-button', {
                key: 'reset-button',
                props: {
                    type: 'default',
                    size: vm._queryConfig.size
                },
                on: {
                    click: debounce(vm.resetQuery, 300)
                }
            }, vm._queryConfig.resetText),
            h('el-button', {
                key: 'submit-button',
                props: {
                    type: 'primary',
                    size: vm._queryConfig.size,
                    loading: vm._queryConfig.queryLoading && vm.qyLoading
                },
                on: {
                    click: debounce(vm.submitQuery, 300)
                }
            }, vm._queryConfig.submitText),
            vm.hideCollapse ? null : h('el-button', {
                key: 'collapse-button',
                props: {
                    type: 'text',
                },
                on: {
                    click: vm.changeCollapse
                }
            }, [
                vm.collapse ? vm._queryConfig.expandText : vm._queryConfig.collapseText,
                h('i', {'class': vm.collapse ? 'el-icon-arrow-down' : 'el-icon-arrow-up'})
            ])
        ])
    ])
}

export function generatePaginationNode(render, vm) {
    const h = render ? render : vm.$createElement
    const pagination = h('pagination', {
        key: 'pagination-node',
        props: {
            total: vm.pageTotal,
            page: vm.pageParams.pageNum,
            limit: vm.pageParams.pageSize,
            pageSizes: vm._pageConfig.pageSizes
        },
        on: {
            'update:page': (val) => vm.pageParams.pageNum = val,
            'update:limit': (val) => vm.pageParams.pageSize = val,
            'pagination': vm.onPageChange
        }
    })


    let toolbarTitleNode = null
    if (vm.titleTwoRender && typeof vm.titleTwoRender === 'function') {
        toolbarTitleNode = h('div', {
            key: 'title-two-bar-con',
            'class': 'query-table-toolbar-title-two'
        }, [
            vm.titleTwoRender(h, {instance: vm})
        ])
    }

    // let tmp = h('span', 'haha')
    // console.log('titleRender=', titleRender);

    return h('div', {
        ref: REF_PAGEBAR_C,
        'class': 'query-table-page',
    }, [pagination])
}


export function generatePaginationTwoNode(render, vm) {
    const h = render ? render : vm.$createElement
    const pagination = h('pagination', {
        key: 'pagination-node-two',
        props: {
            total: vm.pageTotalTwo,
            page: vm.pageParamsTwo.pageNum,
            limit: vm.pageParamsTwo.pageSize,
            pageSizes: vm.pageParamsTwo.pageSizes
        },
        on: {
            'update:page': (val) => vm.pageParamsTwo.pageNum = val,
            'update:limit': (val) => vm.pageParamsTwo.pageSize = val,
            'pagination': vm.onPageChangeTwo
        }
    })

    return h('div', {
        ref: REF_PAGEBAR_C,
        'class': 'query-table-page-two',
    }, [pagination])
}

export function generateToolbarNode(render, vm) {
    const h = render ? render : vm.$createElement

    let toolbarTitleNode = null
    if (vm.titleRender && typeof vm.titleRender === 'function') {
        toolbarTitleNode = h('div', {
            key: 'title-bar-con',
            'class': 'query-table-toolbar-title'
        }, [
            vm.titleRender(h, {instance: vm})
        ])
    }
    let toolbarButtonNode = null
    if (vm.toolbarRender && typeof vm.toolbarRender === 'function') {

        const handleScroll = (event) => {
            event.stopPropagation()
            event.preventDefault()
            const eventDelta = -event.wheelDelta || event.deltaY * 40
            // const $scrollWrapper = this.scrollWrapper
            vm.$refs['toolbar-scroll-inner'].scrollLeft = vm.$refs['toolbar-scroll-inner'].scrollLeft + eventDelta / 4
        }

        setTimeout(() =>{
          if(vm.$refs['toolbar-scroll-inner']){
            vm.$refs['toolbar-scroll-inner'].scrollLeft = 99999
          }
        }, 240)

        const innerScrollNode = h('div', {
            ref: 'toolbar-scroll-inner',
            'class': 'toolbar-scroll-inner',
            on:{
                wheel: handleScroll
            }
        }, [
            vm.toolbarRender(h, {instance: vm})
        ])

        toolbarButtonNode = h('div', {
            key: 'toolbar-con',
            'class': 'query-table-toolbar-operator',
        },[innerScrollNode])
    }

    let tableToolNode = h('table-tool', {
        props:{
            columns: vm.tableColumn,
            config: vm._toolConfig,
            size: vm._tableConfig.tableSize
        },
        on:{
            'tool-size': size => vm.tableSizeChange(size),
            'tool-refresh': vm.refreshTable,
            'tool-column': value => vm.tableColumnChange(value),
        }
    })

    return h('div', {
        ref: REF_TOOLBAR_C,
        'class': 'query-table-toolbar'
    }, [
        toolbarTitleNode,
        toolbarButtonNode,
        tableToolNode
    ])
}

export function getBatchHandlerButton(render, vm, type, text) {
    const h = render ? render : vm.$createElement
    return h('el-button', {
        props: {
            type: type,
            size: vm._tableConfig.tableSize,
            loading: vm.batchLoading
        },
        on: {
            click: () => {
                vm.batchLoading = true
                vm.batchHandler(vm.allSelections.slice(0), this).then(result => {
                    if (result) {
                        vm.clearSelection(true)
                    }
                }).finally(() => {
                    vm.batchLoading = false
                })
            }
        }
    }, text)
}

export function getBatchCancelButton(render, vm, type, text) {
    const h = render ? render : vm.$createElement
    return h('el-button', {
        props: {
            type: type,
            size: vm._tableConfig.tableSize
        },
        on: {
            click: () => vm.clearSelection(false)
        }
    }, text)
}

export function generateBatchBarNode(render, vm) {
    const h = render ? render : vm.$createElement

    const batchHandlerNode = getBatchHandlerButton(h, vm, 'text', vm._batchConfig.batchText)
    const batchClearNode = getBatchCancelButton(h, vm, 'text', vm._batchConfig.clearText)
    const batchMessageNode = h('div', {
        style: {marginRight: `${vm._layoutConfig.padding}px`}
    }, [
        h('i', {'class': 'el-icon-info', style: {color: '#1890FF', marginRight: '8px'}}, null),
        h('span', null, '已选择'),
        h('span', {style: {color: '#1890FF', margin: '0 4px'}}, vm.allSelections.length),
        h('span', null, '项'),
    ])

    let batchBarContent = null
    if (vm.batchBarRender && typeof vm.batchBarRender === 'function') {
        batchBarContent = vm.batchBarRender(h, {
            records: vm.allSelections,
            instance: vm
        }, [batchClearNode, batchHandlerNode])
    } else {
        batchBarContent = h('div', {
            'class': 'query-table-batchbar-content',
            style: {
                padding: `0 ${vm._layoutConfig.padding[1]}px 0 ${vm._layoutConfig.padding[3]}px`
            }
        }, [
            batchMessageNode,
            batchClearNode,
            vm._batchConfig.showBarHandler ? batchHandlerNode : null
        ])
    }

    return h('div', {
        ref: REF_BATCHBAR_C,
        key: REF_BATCHBAR_C,
        'class': 'query-table-batchbar',
    }, [batchBarContent])
}

export function generateBatchFooterNode(render, vm) {
    const h = render ? render : vm.$createElement

    const batchSubmitNode = getBatchHandlerButton(h, vm, 'primary', vm._batchConfig.batchText)
    const batchCancelNode = getBatchCancelButton(h, vm, 'default', vm._batchConfig.cancelText)

    return h('div', {
        key: 'batchfooter-con',
        'class': 'query-con-batchfooter',
        style: {
            padding: `0 ${vm._layoutConfig.padding[1]}px 0 ${vm._layoutConfig.padding[3]}px`
        }
    }, [batchCancelNode, batchSubmitNode])
}

export function generateColumnOperators(scoped, column, render, vm) {
    const h = render ? render : vm.$createElement
    let operators = []
    if (Array.isArray(column.operators) && column.operators.length) {
        // console.log('1');
        operators = column.operators
    } else if (typeof column.operators === 'function') {
        // console.log('2');
        operators = column.operators( scoped.row, {instance: vm}) || []
    }
    // console.log('operators=', operators);
    if (!operators.length) return null

    // const filterOperators = operators.filter(opt => opt)
    const filterOperators = operators.filter(opt => !!opt && (!opt.permissions || checkButtonPermission(opt.permissions)))

    if (!filterOperators.length) return null

    let [operator1, operator2, operator3, ...operatorRest] = filterOperators
    const operatorNodes = []
    const splitNode = h('span', {'class': 'column-operator-split'}, '|')

    let operatorCallback = null
    if (column.operatorCallback && typeof column.operatorCallback === 'function') {
        // console.log('1');
        operatorCallback = debounce((command) => column.operatorCallback(command, scoped.row, scoped), 300)
    } else {
        // console.log('2');
        operatorCallback = debounce((command) => {
            vm.$emit('on-operator', command, scoped.row, scoped)
        }, 300)
    }

    const getOperatorButton = (operator) => {
        let buttonNode

        if('VNode' === operator.constructor.name){
            return operator
        }
        if (operator.confirm && !operator.disabled) {
            buttonNode = h('el-popconfirm', {
                props: {
                    confirmButtonText: operator.confirm?.submitText || '确定',
                    cancelButtonText: operator.confirm?.cancelText || '取消',
                    icon: operator.confirm?.icon || "el-icon-info",
                    iconColor: operator.confirm?.iconColor || "red",
                    title: operator.confirm?.title || "确定要删除吗？"
                },
                on: {
                    confirm: operatorCallback.bind(null, operator.command)
                }
            }, [h('el-button', {
                props: {
                    type: 'text',
                    size: vm._tableConfig.tableSize
                },
                slot: "reference",
            }, operator.label)])
        } else {
            buttonNode = h('el-button', {
                key: 'operator-'+operator.command,
                props: {
                    type: 'text',
                    size: vm._tableConfig.tableSize,
                    disabled: operator.disabled
                },
                on: {
                    click: operatorCallback.bind(null, operator.command)
                }
            }, operator.label)
        }

        return buttonNode
    }
    if (operator1) {
        operatorNodes.push(getOperatorButton(operator1))
    }
    if (operator2) {
        operatorNodes.push(splitNode)
        operatorNodes.push(getOperatorButton(operator2))
    }
    if (operator3) {
        if (!operatorRest.length) {
            operatorNodes.push(splitNode)
            operatorNodes.push(getOperatorButton(operator3))
        } else {
            operatorRest.unshift(operator3)

            const elDropdownMenuNode = h('el-dropdown-menu', {
                slot: 'dropdown'
            }, operatorRest.map(item => {
                return h('el-dropdown-item', {
                    key: item.command,
                    props: {
                        command: item.command,
                        disabled: item.disabled,
                    }
                }, item.label)
            }))
            const moreDropdown = h('el-dropdown', {
                props: {
                    type: 'text',
                    size: vm._tableConfig.tableSize,
                    splitButton: true,
                },
                on: {
                    command: operatorCallback
                }
            }, ['更多', elDropdownMenuNode])

            operatorNodes.push(splitNode)
            operatorNodes.push(moreDropdown)
        }
    }
    return h('div', {
        'class': 'column-operator'
    }, operatorNodes)
}

export function tableColumnRender(scoped, column, render, vm) {
    const h = render ? render : vm.$createElement

    let defaultRender = scoped.row[column.prop]

    let selectOption
    if ('select' === column.type) {
        if (column.valueEnum) {
            selectOption = column.valueEnum[scoped.row[column.prop]]
            if (!!selectOption) {
                defaultRender = selectOption.text
            }
        } else if (column.options) {
            selectOption = column.options.find(item => item.value == defaultRender)
            if (!!selectOption) {
                defaultRender = selectOption.label
            }
        } else if (column.request) {
            selectOption = column._columnRequestOptions.find(item => item.value == defaultRender)
            if (!!selectOption) {
                defaultRender = selectOption.label
            }
        }
    } else if ('money' === column.type) {
        if (!isNaN(parseFloat(defaultRender))) {
            defaultRender = formatNumber(parseFloat(defaultRender))
        }
    }

    if (column.render && typeof column.render === 'function') {
        defaultRender = column.render(h, defaultRender, {
            record: scoped.row,
            scoped: scoped,
            selectOption: selectOption,
            pageParams: vm.pageParams,
            instance: vm
        })
    }

    if((defaultRender === null || defaultRender === undefined) && column.defaultValue){
        defaultRender = column.defaultValue
    }

    return defaultRender
}

/**
 * 第二个表格
 * @param {*} column 
 * @param {*} render 
 * @param {*} vm 
 * @param {*} tableTwoPage 是否分页
 */
export function generateColumnScopedDefaultTwo(column, render, vm, tableTwoPage) {
    // console.log('generateColumnScopedDefaultTwo');
    let scopedSlots = null
    if (['selection', 'expand'].some(type => type === column.type)) {
        scopedSlots = null
    } else if ('index' === column.type) {
        // console.log('eeeee');
        if (column.increment) {
            scopedSlots = {
                default: scoped => scoped.$index + 1
                    + (tableTwoPage == true ? ((vm.pageParamsTwo.pageNum - vm._pageConfig.startPage) * vm.pageParamsTwo.pageSize) : 0)
            }
        }
    } else if ('operator' === column.type) {
        scopedSlots =  {
            default: scoped => {
                return column.operators ? generateColumnOperators(scoped, column, render, vm) : null
            }
        }
    } else {
        scopedSlots = {
            default: scoped => tableColumnRender(scoped, column, render, vm)
        }
    }

    return scopedSlots
}

export function generateColumnScopedDefault(column, render, vm) {
    let scopedSlots = null
    if (['selection', 'expand'].some(type => type === column.type)) {
        scopedSlots = null
    } else if ('index' === column.type) {
        if (column.increment) {
            scopedSlots = {
                default: scoped => scoped.$index + 1
                    + (vm.pageParams.pageNum - vm._pageConfig.startPage) * vm.pageParams.pageSize
            }
        }
    } else if ('operator' === column.type) {
        scopedSlots =  {
            default: scoped => {
                return column.operators ? generateColumnOperators(scoped, column, render, vm) : null
            }
        }
    } else {
        scopedSlots = {
            default: scoped => tableColumnRender(scoped, column, render, vm)
        }
    }

    return scopedSlots
}
